﻿using System;
using System.Linq;

namespace SQLPXBase.Factory.Keys.KeyModels
{
    public class HomogeneousPK<T>:PrimaryKey
        where T : struct
    {
        private T?[] keys;

        #region Constructor

        public HomogeneousPK(int keyCount)
        {
            keys = new T?[keyCount];
        }

        //public HomogeneousPK(DataRow rw, string[] fieldNames, int keyCount) : base(rw, fieldNames)
        //{
        //    keys = new T?[keyCount];
        //}

        #endregion

        public override int KeyLength
        {
            get { return keys.Length; }
        }

        public override bool IsEmpty
        {
            get
            {
                return !keys.Any(key => key.HasValue);
            }
        }

        public override PrimaryKey DefaultValue
        {
            get { return new HomogeneousPK<T>(keys.Length); }
        }

        public override object GetSingleValue
        {
            get
            {
                return KeyLength == 1 ? keys[0] : null;
            }
        }

        public override object[] GetValues
        {
            get { return new object[] {keys}; }
        }

        public override void SetValues(object[] values)
        {
            CheckValues(values);

            try
            {
                for (int i = 0; i < values.Length; i++)
                {
                    object v = values[i];
                    keys[i] = (T?) v;
                }
            }
            catch (Exception ex)
            {
                throw new PrimaryKeyException(ex.Message, ex);
            }
        }
    }
}
